const multer = require('@koa/multer');
const { uploadToOSS } = require('@/config/oss');
const path = require('path');

class UploadController {
    constructor() {
        // 配置multer用于处理文件上传
        this.upload = multer({
            storage: multer.memoryStorage(), // 使用内存存储
            limits: {
                fileSize: 10 * 1024 * 1024, // 限制文件大小为10MB
            },
            fileFilter: (req, file, cb) => {
                // 只允许图片文件
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                if (allowedTypes.includes(file.mimetype)) {
                    cb(null, true);
                } else {
                    cb(new Error('只支持图片文件格式 (JPEG, PNG, GIF, WebP)'), false);
                }
            }
        });
    }

    // 上传图片到OSS
    async uploadImage(ctx) {
        try {
            // 使用multer中间件处理文件上传
            await new Promise((resolve, reject) => {
                this.upload.single('image')(ctx, ctx.res, (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve();
                    }
                });
            });

            const file = ctx.file;
            if (!file) {
                ctx.body = {
                    success: false,
                    message: '请选择要上传的图片文件'
                };
                return;
            }

            console.log('接收到文件:', {
                originalname: file.originalname,
                mimetype: file.mimetype,
                size: file.size
            });

            // 生成带日期的文件名
            const ext = path.extname(file.originalname);
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const dateStr = `${year}-${month}-${day}`;
            const timestamp = Date.now();
            const randomStr = Math.random().toString(36).substring(2);
            const fileName = `${dateStr}-${timestamp}-${randomStr}${ext}`;

            // 上传到OSS
            const uploadResult = await uploadToOSS(file.buffer, fileName, file.mimetype);

            if (uploadResult.success) {
                ctx.body = {
                    success: true,
                    message: '图片上传成功',
                    data: {
                        url: uploadResult.url,
                        fileName: fileName,
                        originalName: file.originalname,
                        size: file.size,
                        mimetype: file.mimetype
                    }
                };
            } else {
                ctx.body = {
                    success: false,
                    message: '图片上传失败: ' + uploadResult.error
                };
            }

        } catch (error) {
            console.error('图片上传处理失败:', error);
            ctx.body = {
                success: false,
                message: '图片上传失败: ' + error.message
            };
        }
    }

    // 处理base64图片上传
    async uploadBase64Image(ctx) {
        try {
            const { imageData, fileName } = ctx.request.body;

            if (!imageData) {
                ctx.body = {
                    success: false,
                    message: '请提供图片数据'
                };
                return;
            }

            // 解析base64数据
            let base64Data = imageData;
            let mimeType = 'image/jpeg'; // 默认类型

            // 检查是否包含data URL前缀
            if (imageData.startsWith('data:')) {
                const matches = imageData.match(/^data:([^;]+);base64,(.+)$/);
                if (matches) {
                    mimeType = matches[1];
                    base64Data = matches[2];
                }
            }

            // 将base64转换为buffer
            const buffer = Buffer.from(base64Data, 'base64');

            // 根据MIME类型确定文件扩展名
            const extMap = {
                'image/jpeg': '.jpg',
                'image/jpg': '.jpg',
                'image/png': '.png',
                'image/gif': '.gif',
                'image/webp': '.webp'
            };

            const ext = extMap[mimeType] || '.jpg';
            
            // 生成带日期的文件名
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const dateStr = `${year}-${month}-${day}`;
            const timestamp = Date.now();
            const randomStr = Math.random().toString(36).substring(2);
            
            const finalFileName = fileName || `${dateStr}-${timestamp}-${randomStr}${ext}`;

            console.log('处理base64图片:', {
                fileName: finalFileName,
                mimeType: mimeType,
                size: buffer.length
            });

            // 上传到OSS
            const uploadResult = await uploadToOSS(buffer, finalFileName, mimeType);

            if (uploadResult.success) {
                ctx.body = {
                    success: true,
                    message: '图片上传成功',
                    data: {
                        url: uploadResult.url,
                        fileName: finalFileName,
                        size: buffer.length,
                        mimetype: mimeType
                    }
                };
            } else {
                ctx.body = {
                    success: false,
                    message: '图片上传失败: ' + uploadResult.error
                };
            }

        } catch (error) {
            console.error('Base64图片上传失败:', error);
            ctx.body = {
                success: false,
                message: '图片上传失败: ' + error.message
            };
        }
    }
}

module.exports = new UploadController();